<template>
	<el-dialog
		:visible.sync="addComShow"
		width="95%"
		:before-close="cancel"
		:fullscreen="true"
		top="3vh"
		:show-close="false"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
	>
		<div slot="title" class="titleSlot">
			<div style="width: 95%;word-break: break-all;">
				公募基金:{{ title }}
				<span style="margin-left: 10px" v-if="['3', '5', '7', '6', '4'].includes(dataType)">{{ updateMsg }}</span>
				<!-- 驳回备注 -->
				<span style="color: red; margin-left: 10px" v-if="['5', '7'].includes(dataType)">驳回原因：{{ addRemark }}</span>
			</div>
			<el-button type="primary" size="mini" icon="el-icon-switch-button" @click="cancel(1)">关 闭</el-button>
		</div>

		<el-steps :active="active" align-center>
			<el-step @click.native="stepClick(item, index)" v-for="(item, index) in stepList" :key="index" aria-disabled="true">
				<div slot="title">{{ item.title }}</div>
				<div slot="icon">
					{{ index + 1 }}
					<!-- 变更复核时，展示具体变更数量 -->
					<span v-if="['6'].includes(dataType)">
						<template v-if="$store.state.fundStep.pulicCheckNum[item.key]">
							<div class="fuhe" v-if="$store.state.fundStep.pulicCheckNum[item.key].num">
								{{ $store.state.fundStep.pulicCheckNum[item.key].num }}
							</div>
						</template>
					</span>
				</div>
			</el-step>
		</el-steps>

		<el-header class="btns">
			<span :class="{ titleColor: title === '复核' && comShow !== 'submitInfo' }">{{ stepTitle }}</span>
			<div>
				<!-- 新增保存、下一步、提交 -->
				<span v-if="['', '1'].includes(dataType)">
					<el-button size="mini" :disabled="loading" type="primary" v-if="comShow !== 'submitInfo'" @click="save(title)">保 存</el-button>
					<el-button size="mini" type="primary" @click="save(title)" v-if="comkey === active && comShow !== 'submitInfo'">下一步</el-button>
					<el-button size="mini" :disabled="loading" type="primary" @click="submit(title)" v-if="comShow === 'submitInfo'">提交</el-button>
				</span>
				<!--  -->

				<!-- 驳回按钮 -->
				<span v-if="title === '复核' && comShow === 'submitInfo'">
					<el-button size="mini" :disabled="loading" type="danger" @click="rejectFund('驳回')">驳回</el-button>
					<el-button size="mini" :disabled="loading" type="warning" @click="rejectFund('确认无误')">确认无误</el-button>
				</span>
				<!--  -->

				<!-- 新增驳回变更保存 -->
				<el-button
					:disabled="loading"
					v-if="title === '重新申请' && comShow === 'submitInfo'"
					@click="againSaveFunc"
					size="mini"
					type="primary"
					>提交</el-button
				>
				<!--  -->

				<!-- 变更保存 -->
				<span v-if="['变更', '清算', '终止', '成立'].includes(title)">
					<el-button
						:disabled="loading"
						v-if="comShow !== 'submitInfo' && dataType !== '7' && title !== '成立'"
						@click="updateSave('保存')"
						size="mini"
						type="primary"
						>保存</el-button
					>
					<el-button :disabled="loading" v-if="comShow === 'submitInfo'" @click="updateSave('提交')" size="mini" type="primary"
						>提交</el-button
					>
				</span>
				<!--  -->
			</div>
		</el-header>
		<div
			v-loading="loading"
			element-loading-text="正在处理中，请稍等......"
			element-loading-spinner="el-icon-loading"
			element-loading-background="rgba(0, 0, 0, 0.8)"
		>
			<el-card class="box-card">
				<baseInfo
					@setpFunc="edit"
					:dataType="dataType"
					:fundSysCode="fundSysCode"
					@resetRate="resetRate"
					@globalFSysCo="globalFSysCo"
					ref="baseInfo"
					:haveYouWalked="haveYouWalked"
					v-show="comShow === 'baseInfo'"
				/>
				<dateInfo
					@setpFunc="edit"
					:fundSysCode="fundSysCode"
					:dataType="dataType"
					:isEnterDateHtmlPro="isEnterDateHtml"
					:haveYouWalked="haveYouWalked"
					ref="dateInfo"
					v-show="comShow === 'dateInfo'"
				/>
				<organInfo
					@setpFunc="edit"
					:fundSysCode="fundSysCode"
					:dataType="dataType"
					:haveYouWalked="haveYouWalked"
					ref="organInfo"
					v-show="comShow === 'organInfo'"
				/>
				<rateInfo
					@setpFunc="edit"
					:fundSysCode="fundSysCode"
					:dataType="dataType"
					:haveYouWalked="haveYouWalked"
					ref="rateInfo"
					v-show="comShow === 'rateInfo'"
				/>
				<investInfo @setpFunc="edit" :fundSysCode="fundSysCode" :dataType="dataType" ref="investInfo" v-show="comShow === 'investInfo'" />
				<fundMange @setpFunc="edit" :fundSysCode="fundSysCode" :dataType="dataType" ref="fundMange" v-show="comShow === 'fundMange'" />
				<fileInfo @setpFunc="edit" :fundSysCode="fundSysCode" :dataType="dataType" ref="fileInfo" v-show="comShow === 'fileInfo'" />
				<submitInfo
					@setpFunc="edit"
					:fundSysCode="fundSysCode"
					:dataType="dataType"
					:isEnterDateHtmlPro="isEnterDateHtml"
					@loadingShow="loadingShow"
					@submitSuccess="submitSuccess"
					ref="submitInfo"
					v-show="comShow === 'submitInfo'"
				/>
			</el-card>
		</div>
	</el-dialog>
</template>
<script>
	import baseInfo from './steps/baseInfo/index' // 基础信息
	import dateInfo from './steps/dateInfo/index' // 重要日期
	import organInfo from './steps/organInfo/index' // 机构信息
	import rateInfo from './steps/rateInfo/index' // 费率信息
	import investInfo from './steps/investInfo/index' // 投资相关
	import fundMange from './steps/fundMange/index' // 基金经理
	import fileInfo from './steps/fileInfo/index' // 文件信息
	import submitInfo from './steps/submitInfo/index' // 提交信息
	import {
		seachStep,
		addCheckReject,
		againSave,
		updateSaveInfo,
		updateSaveFund,
		updateSubmitFund,
		checkBtn,
		newEdiSubmit,
		fundEsablish
	} from '@/api/productApi/infoMain'
	import { updateCompareSubmit } from './dataCheck'
	import { completionFunc } from './dataCompletion'
	import { jsonArray } from '@/api/productApi/file'
	import {
		stepIsSuccess,
		templateTitle,
		notEmpty,
		returnEstablished,
		updateSaveData,
		submitData1,
		submitData2,
		checkoutData1,
		checkoutData2,
		updateLastTile,
		reapplyData
	} from './handler.js'
	import { returnData } from '@/utils/dataType'
	export default {
		components: {
			baseInfo,
			dateInfo,
			organInfo,
			rateInfo,
			investInfo,
			fundMange,
			fileInfo,
			submitInfo
		},
		props: {
			title: {
				type: String,
				default: ''
			},
			addComShow: {
				type: Boolean,
				default: false
			},
			comIsShow: {
				type: Function,
				default: Function
			},
			queryFundManagerList: {
				type: Function,
				default: Function
			},
			comIsShowKey: {
				type: Function,
				default: Function
			}
		},
		computed: {
			comShow: {
				set(index) {
					this.comkey = index
				},
				get() {
					return this.stepList[this.comkey].key
				}
			}
		},
		data() {
			return {
				active: 0, // 步骤key
				stepList: [
					{ title: '产品基础信息', key: 'baseInfo' },
					{ title: '重要日期信息', key: 'dateInfo' },
					{ title: '机构信息', key: 'organInfo' },
					{ title: '费率信息', key: 'rateInfo' },
					{ title: '投资相关信息', key: 'investInfo' },
					{ title: '基金经理信息', key: 'fundMange' },
					{ title: '文件上传信息', key: 'fileInfo' },
					{ title: '完成', key: 'submitInfo' }
				],
				stepTitle: '基础信息',
				comkey: 0, // 组件key,
				fundSysCode: '',
				dataType: '',
				submitInfo: {},
				addRemark: '',
				updateMsg: '',
				totalData: {},
				isEnterDateHtml: '',
				loading: false,
				tempalteCode: '',
				haveYouWalked: {} // 判断新增时该步骤是否走过
			}
		},
		mounted() {
			this.isCom(0)
		},
		methods: {
			// 提交成功
			submitSuccess() {
				this.cancel()
			},

			// 添加loading
			loadingShow(data) {
				this.loading = data
			},

			// 变更
			async updateSave(type) {
				let isSubmit = []
				if (!['fundMange', 'submitInfo'].includes(this.comShow)) {
					if (returnData(this.$refs[this.comShow].ValidationRequired()) === 'Object') {
						// 费率非法
						return
					}
					isSubmit = this.$refs[this.comShow].ValidationRequired()
				}
				// 将编辑的数据集中到全局
				this.stepList.forEach((item, index) => {
					this.$refs[item.key].updateStoreData()
					if ('isCheck' in this.$refs[this.comShow]) {
						this.$refs[this.comShow].isCheck = true
					}
				})
				const msgList = this.$refs.submitInfo.ValidationRequired() // 验证完成页面必填项是否已经填写
				if (this.isEnterDateHtml === '3') {
					// 成立
					this.CustomtextComfirm(() => {
						const form = returnEstablished()
						fundEsablish(form).then(res => {
							if (res.msgCode === 'Y') {
								this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
								this.cancel()
							}
						})
					}, `${msgList.length ? `必填项 “ ${msgList.join('、')} ” 未填写，是否确认提交？` : `此操作将永久成立基金，是否继续？`}`)
					return false
				}
				// 收集变更项
				updateCompareSubmit()
				if (this.dataType === '3') {
					let msg = isSubmit.join('、')
					if (type === '提交') {
						msg = msgList.join('、')
					} else {
						msg = isSubmit.join('、')
					}
					this.CustomtextComfirm(async () => {
						if (type === '保存') {
							const form = updateSaveData()
							// 变更保存
							if (this.comShow === 'fundMange') {
								// 保存经理经理信息
								this.loadingShow(true) // 开启loading
								updateSaveFund(form).then(res => {
									if (res.msgCode === 'Y') {
										this.$refs.fundMange.getNewfundMange()
										this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
									}
									this.loadingShow(false) // 关闭loading
								})
							} else {
								form.recordFundChangeInfo = form.fundCustodianInfo
								this.loadingShow(true) // 开启loading
								await updateSaveInfo(form).then(res => {
									if (res.msgCode === 'Y') {
										this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
									}
									this.loadingShow(false) // 关闭loading
								})
								setTimeout(() => {
									if ('isCheck' in this.$refs[this.comShow]) {
										this.$refs[this.comShow].isCheck = false
									}
								})
							}
						} else if (type === '提交') {
							// 变更','清算','终止','成立' 提交
							const form = submitData1(this)
							this.loadingShow(true) // 开启loading
							updateSubmitFund(form).then(res => {
								if (res.msgCode === 'Y') {
									this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
									this.cancel()
								}
								this.loadingShow(false) // 关闭loading
							})
						}
					}, `${['fundMange'].includes(this.comShow) || !msg ? '此操作将永久提交已编辑数据，是否继续？' : `必填项 “ ${msg} ” 未填写，是否确认提交?`}`)
				} else if (this.dataType === '7') {
					// 变更','清算','终止',  提交
					this.CustomtextComfirm(() => {
						const form = submitData2(this)
						this.loadingShow(true) // 开启loading
						newEdiSubmit(form).then(res => {
							if (res.msgCode === 'Y') {
								this.cancel()
								this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
							}
							this.loadingShow(false) // 关闭loading
						})
					}, `${msgList.length ? `必填项 “ ${msgList.join('、')} ” 未填写，是否确认提交？` : `此操作将永久提交已编辑数据，是否继续？`}`)
				}
			},

			// 重新编辑保存
			againSaveFunc() {
				const list = []
				// 将数据集中到全局
				this.stepList.forEach((item, index) => {
					if (this.$refs[item.key]) {
						this.$refs[item.key].updateStoreData()
						if (!['fundMange'].includes(item.key)) {
							if ('isCheck' in this.$refs[item.key]) {
								this.$refs[item.key].isCheck = true
							}
							list.push(this.$refs[item.key].ValidationRequired())
						}
					}
				})
				if (list.some(item => returnData(item) === 'Object')) {
					return
				}
				const msgList = this.$refs.submitInfo.ValidationRequired() // 验证完成页面必填项是否已经填写
				const form = reapplyData()
				if (form) {
					this.CustomtextComfirm(() => {
						this.loadingShow(true)
						againSave(form).then(res => {
							if (res.msgCode === 'Y') {
								this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
								this.cancel()
							}
							this.loadingShow(false)
						})
					}, `${msgList.length ? `必填项 “ ${msgList.join('、')} ” 未填写，是否确认提交？` : `此操作将永久提交已编辑数据，是否继续？`}`)
				}
			},

			// 复核
			rejectFund(type) {
				if (this.dataType === '4') {
					const obj = checkoutData1(this, type)
					if (type === '确认无误') {
						this.operatorComfirm(() => {
							this.loadingShow(true)
							addCheckReject(obj).then(res => {
								if (res.msgCode === 'Y') {
									this.cancel()
									this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
								}
								this.loadingShow(false)
							})
						}, '确定复核')
					} else {
						this.$prompt('请输入驳回备注', '提示', {
							confirmButtonText: '确定',
							concelButtonText: '取消',
							inputPattern: /[^\\s\ \r\\n]/,
							inputErrorMessage: '请输入驳回备注'
						}).then(({ value }) => {
							obj.rejectRemark = value
							this.loadingShow(true)
							addCheckReject(obj).then(res => {
								if (res.msgCode === 'Y') {
									this.cancel()
									this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
								}
								this.loadingShow(false)
							})
						})
					}
				} else {
					const obj = checkoutData2(this, type)
					if (type === '确认无误') {
						this.operatorComfirm(() => {
							this.loadingShow(true)
							checkBtn(obj).then(res => {
								if (res.msgCode === 'Y') {
									this.cancel()
									this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
								}
								this.loadingShow(false)
							})
						}, '确定复核')
					} else {
						this.$prompt('请输入驳回备注', '提示', {
							confirmButtonText: '确定',
							concelButtonText: '取消',
							inputPattern: /[^\\s\ \r\\n]/,
							inputErrorMessage: '请输入驳回备注'
						}).then(({ value }) => {
							obj.rejectRemark = value
							this.loadingShow(true)
							checkBtn(obj).then(res => {
								if (res.msgCode === 'Y') {
									this.cancel()
									this.$message({ type: 'success', customClass: 'el-messageClass', message: res.msg })
								}
								this.loadingShow(false)
							})
						})
					}
				}
			},

			// 默认显示
			isCom(index) {
				this.comkey = index
				this.stepTitle = this.stepList[this.comkey].title
			},

			// 重置费率
			resetRate(num, list) {
				this.$refs.rateInfo.resetRate(num, list)
			},

			// 步骤点击
			async stepClick(item, num) {
				if (this.dataType === '1') {
					const stepForward = this.stepList[this.active] // 已经走到的最新的步骤
					const nowStep = this.comShow // 切换前的步骤
					//  点击步骤 <= 当前走到的最新步骤
					if (num <= this.active) {
						// 走到的最新的步骤!== 当切换前的步骤 && 点击的步骤 !== 当前步骤
						if (stepForward.key !== nowStep && this.stepList[num].key !== nowStep) {
							const saveFlag = await this.$refs[nowStep].switchingSteps()
							if (!saveFlag) {
								return false
							}
						}
					}
				}
				if (this.active >= this.stepList.findIndex(items => items.key === item.key)) {
					this.comkey = this.stepList.findIndex(items => items.key === item.key)
					this.stepTitle = this.stepList[this.comkey].title // 当前步骤title
				}
				const LinkageList = ['rateInfo', 'dateInfo', 'fileInfo'] // 需要联动的页面标识
				if (LinkageList.includes(this.comShow) && this.dataType !== '1') {
					// 当不是新增/完善信息流程时 数据联动全局
					this.stepList.forEach((item, index) => {
						// 将每个步骤的数据集中到store
						this.$refs[item.key].updateStoreData()
					})
					this.$refs[this.comShow].getData()
				}
			},

			// 提交
			submit() {
				// 将数据集中到全局
				this.stepList.forEach((item, index) => {
					if (this.$refs[item.key]) {
						this.$refs[item.key].updateStoreData()
						if (!['fundMange'].includes(item.key)) {
							if ('isCheck' in this.$refs[item.key]) {
								this.$refs[item.key].isCheck = true
							}
						}
					}
				})
				this.$refs.submitInfo.save()
			},

			async cancel(num) {
				await this.$store.dispatch('fundStep/resetNum')
				this.$emit('comIsShow')
				this.$emit('comIsShowKey')
				this.$emit('queryFundManagerList', num)
			},

			// 新增第一步将系统代码响应全局
			globalFSysCo(fundSysCode) {
				this.fundSysCode = fundSysCode
			},

			// 保存
			save() {
				if (this.comkey === this.active) {
					this.$refs[this.comShow].startDown('下一步')
				} else {
					this.$refs[this.comShow].startDown('保存')
				}
			},

			edit(type, fundSysCode, isEnterDateHtml, num) {
				this.fundSysCode = fundSysCode
				this.isEnterDateHtml = isEnterDateHtml || ''
				this.dataType = type
				const params = {
					fundRaiseType: '1',
					fundSysCode: fundSysCode,
					filedCheckStatus: type === '5' || type === '7' ? '2' : '0'
				}
				this.loadingShow(true)
				seachStep(params).then(res => {
					if (res.msgCode === 'Y') {
						res.data.body = completionFunc(jsonArray(res.data.body), this.title)
						if (['3', '7', '6'].includes(type)) {
							// 变更、复核、终止、清算、成立时将数据集中到全局
							this.$store.state.fundStep.pucliktTotalData = res.data.body
						}
						// 判断该步骤是否已经走过
						if (!!res.data.body.recordFundAddInfo && !num) {
							stepIsSuccess(res, this)
							this.haveYouWalked = jsonArray(res.data.body.recordFundAddInfo ? res.data.body.recordFundAddInfo : {})
						}

						// 主表(已通过审核),dataStatus为1，则代表申请表没有数据
						if (['成立', '查看'].includes(this.title) || res.data.body.dataStatus === '1') {
							if (res.data.body.fundCustodianInfo) {
								res.data.body.productFundInfo.baseInfo.personLiableName = res.data.body.fundCustodianInfo.personLiableName
								this.submitInfo = res.data.body.fundCustodianInfo
							}
							this.$store.state.fundStep.publicBaseInfo = jsonArray(res.data.body.productFundInfo.baseInfo)
							this.$nextTick(() => {
								this.$refs.baseInfo.edit(res.data.body.productFundInfo.baseInfo) // 基础信息
								this.$refs.dateInfo.edit(res.data.body.productFundInfo.dateInfo) // 重要日期
								this.$refs.organInfo.edit(res.data.body.productFundInfo.organInfo) // 机构信息
								this.$refs.rateInfo.edit(res) // 费率信息
								this.$refs.investInfo.edit(res.data.body.productFundInfo.investInfo) // 投资相关信息
								this.$refs.fileInfo.edit(res.data.body) // 文件信息
								this.$refs.submitInfo.edit(res.data.body.fundCustodianInfo) // 提交信息
							})
							if (['3', '5', '7', '6', '4'].includes(this.dataType)) {
								// 基金代码拼基金名称
								this.updateMsg = templateTitle(res.data.body.productFundInfo)
							}
						}
						// 基金经理
						this.$nextTick(() => {
							// 一次变更 || 变更临时保存
							if (['3'].includes(type)) {
								if (
									res.data.body.fundManagerApplyList &&
									Array.isArray(res.data.body.fundManagerApplyList) &&
									res.data.body.fundManagerApplyList.length
								) {
									this.$refs.fundMange.edit(res.data.body.fundManagerApplyList)
								} else {
									this.$refs.fundMange.edit(res.data.body.fundManagerInfoList)
								}
							}
							// 查看
							if (['2'].includes(type)) {
								this.$refs.fundMange.edit(res.data.body.fundManagerInfoList)
							}
							// 变更、清算、终止、复核、完善信息、重新申请  7('变更', '清算', '终止' 变更被驳回)
							if (['7', '4', '6', '1', '5'].includes(type)) {
								// 基金经理信息
								this.$refs.fundMange.edit(res.data.body.fundManagerApplyList)
							}
						})
						// 申请表(未通过审核)
						if (!['成立', '查看'].includes(this.title) && res.data.body.dataStatus !== '1') {
							if (res.data.body.fundCustodianInfo) {
								res.data.body.productFundApply.baseInfo.personLiableName = res.data.body.fundCustodianInfo.personLiableName
								this.submitInfo = res.data.body.fundCustodianInfo
							}
							this.$store.state.fundStep.publicBaseInfo = jsonArray(res.data.body.productFundApply.baseInfo)
							this.$nextTick(() => {
								this.$refs.baseInfo.edit(res.data.body.productFundApply.baseInfo) // 基础信息
								this.$refs.dateInfo.edit(res.data.body.productFundApply.dateInfo) // 重要日期
								this.$refs.organInfo.edit(res.data.body.productFundApply.organInfo) // 机构信息
								this.$refs.rateInfo.edit(res) // 费率信息
								this.$refs.investInfo.edit(res.data.body.productFundApply.investInfo) // 投资相关信息
								this.$refs.fileInfo.edit(res.data.body) // 文件信息
								this.$refs.submitInfo.edit(res.data.body.fundCustodianInfo) // 提交信息
							})
							if (['3', '5', '7', '6', '4'].includes(this.dataType)) {
								// 基金代码拼基金名称
								this.updateMsg = templateTitle(res.data.body.productFundApply)
							}
							// 新增驳回备注
							this.addRemark = notEmpty(res.data.body.recordFundAddInfo.remark)
						}

						if (this.dataType === '7') {
							// 其他驳回备注
							this.addRemark = notEmpty(res.data.body.recordFundChangeInfo.checkRemark)
						}

						if (['查看', '复核'].includes(this.title)) {
							this.active = this.stepList.length - 1
							if (this.title === '查看') {
								// 当处于查看状态时，去掉最后一个步骤
								this.stepList.splice(this.stepList.length - 1, 1)
								this.active = this.stepList.length - 1
							} else {
								// 改变最后步骤标题
								updateLastTile(this)
							}
							this.isCom(0)
							this.stepList.forEach(item => {
								// 将每个步骤的表单设置为不可编辑的状态
								this.$refs[item.key].isBaseDisabledCom(true, false)
							})
						}

						if (['变更', '终止', '清算', '成立', '重新申请'].includes(this.title) || !!this.tempalteCode) {
							this.comShow = this.stepList.length - 1
							this.active = this.stepList.length - 1
							// 改变最后步骤标题
							updateLastTile(this)
							this.$nextTick(() => {
								this.comShow = ['清算', '终止', '成立'].includes(this.title) ? 1 : 0 // 重要日期信息 ： 基础信息
								this.stepTitle = this.stepList[this.comkey].title // 步骤标题
								this.tempalteCode = ''
							})
						}
					}
					this.loadingShow(false)
				})
			},

			// 复制模板
			templateChange(fundSysCode) {
				this.tempalteCode = fundSysCode
				setTimeout(() => {
					this.$message({ type: 'success', message: '复制成功' })
				}, 100)
			}
		}
	}
</script>
<style lang="scss" scoped src='./index.scss'></style>
